import React, { useState, memo, useEffect, useRef } from 'react';
import { Row, Col, message, Switch, Button } from 'tdesign-react';
import {getArtClassListApi, getListApi, createApi, putApi } from 'api/operation/banner';
import { uploadFileApi } from 'api/common';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import SakuraModal from 'components/SakuraModal';
import { IModalRef } from 'components/SakuraModal/types';
import { BLOG_CATEGORY_MAP, getBLOG_CATEGORY_MAP, handleUpdateStatus, PARRENT_TYPE_OPTIONS, type_MAP } from './consts';
import IppeakTable from 'components/IppeakTable';
import StatusSwitch from 'components/StatusSwitch';
import IppeakImage from 'components/IppeakImage';
import SakuraDrawer from 'components/SakuraDrawer';
// import DrawerDetail from 'components/DrawerDetail';
import DetailDrawer from './detail';
import MultiLineText from 'components/MultiLineText';

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailItem, setDetailItem] = useState<any>(null);
  const { loading, setLoading } = useLoading(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const modalRef = useRef<IModalRef | any>(null);
  const [artClassList, setArtClassList] = useState<any[]>([]);
  const [ARTCLASSMAP, setARTCLASSMAP] = useState<any>([]);

  // 获取BANNER_ARTCLASSMAP的函数
  const getBANNER_ARTCLASSMAP = () => {
    return localStorage.getItem('BANNER_ARTCLASSMAP') ? JSON.parse(localStorage.getItem('BANNER_ARTCLASSMAP') || '') : [];
  };
  const initData = {
    status: 1,
    pack_type: '1',
    order_type: 9,
    email: '',
  };
  const fields: any[] = [
    { label: '邮箱', name: 'email', type: 'input', required: true },
    {
      label: '套餐类型',
      name: 'pack_type',
      type: 'select',
      options: [{ label: '流量', value: 1 }],
      required: true,
      disabled: true,
    },
    { label: '流量', name: 'flow', type: 'input', required: true, appendSuffix: 'G' },
    { label: '时效', name: 'day', type: 'input', required: true, appendSuffix: '天' },
    {
      label: '订单类型',
      name: 'order_type',
      type: 'select',
      options: [],
      disabled: true,
      help: '试用订单仅对没有GB套餐的用户生效；',
    },
    { label: '备注', name: 'remarks', type: 'textarea', props: { autosize: { minRows: 3, maxRows: 10 } } },
  ];
  const columns = createColumns([
    {
      label: 'ID',
      key: 'id',
    },
    {
      label: '位置',
      key: 'position',
      width: '190',
    },
    {
      label:'banner-中文',
      key: 'banner_image',
      width: '230',
      render: ({ row }: any) => (
          row.banner_image ? (
            <IppeakImage 
              src={row.banner_image}
              width={200}
              height={100}
              fit="cover"
              shape="round"    
              alt="banner-中文图"
            />
          ) : (
            <span>-</span>
          )
      ),
    },
    {
      label:'跳转链接-中文',
      key:'jump_link',
      width: '250',
      render: ({ row }: any) => (
        <MultiLineText value={row.jump_link || '-'}  maxLines={3}
        lineHeight={20}></MultiLineText>
      ),
    },
    {
      label: '排序',
      key: 'sort',
    },
    {
      label: '状态',
      key: 'region',
      render: ({ row }: any) => (
        <StatusSwitch
          value={!row.deleted}
          loading={updatingRows.has(row.id)}
          onChange={(newValue) => handleUpdateStatus(newValue, row, setUpdatingRows, setTable)}
          row={row}
          activeText="启用"
          inactiveText="禁用"
        />
      ),
    },
    {
      label: '操作人',
      key: 'creator',
      width: '150',
    },
    {
      label: '操作时间',
      key:'created',
      width: '150',
      type:'date'
    },
    {
      label: '操作',
      key: 'op',
      fixed: 'right',
      width: '150',
              render: ({ row }: any) => (
         <>
         <Button  theme='primary' variant='text' onClick={() => handleDetailClick(row)}>
           详情
          </Button>
         <Button  theme='primary' variant='text' onClick={() => handleEditClick(row)}>
         编辑
       </Button></>
      ),
    },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const [updatingRows, setUpdatingRows] = useState<Set<string | number>>(new Set());
  const drawerRef = useRef<any>(null);
  const formFields: any[] = [
    {
      label:'位置',
      name:'art_class',
      type:'select',
      options: getBANNER_ARTCLASSMAP(),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
  ];
  const { list, total, current, pageSize } = table;
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      const res: any = await getListApi({ ...params, ...query });
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results.map((item: any) => {
          // 映射图片字段，确保表格能正确显示图片
          const mappedItem = {
            ...item,
            art_class: item.art_class, // 保持原始ID值用于表单编辑
            art_class_en: item.art_class, // 保持向后兼容
            // 映射中文图片
            banner_image: item.i18n?.['zh-CN']?.src ? 
              (item.host ? item.host + item.i18n['zh-CN'].src : item.i18n['zh-CN'].src) : 
              item.banner_image,
            // 映射英文图片
            en_banner_image: item.i18n?.['en-US']?.src ? 
              (item.host ? item.host + item.i18n['en-US'].src : item.i18n['en-US'].src) : 
              item.en_banner_image,
            // 映射跳转链接
            jump_link: item.i18n?.['zh-CN']?.href || item.jump_link,
            en_jump_link: item.i18n?.['en-US']?.href || item.en_jump_link,
          };
          return mappedItem;
        }) || [],
        total: res.total || 0,
        pageSize: res.page_size || 10,
        current: res.page || 1,
      }));
    } catch (err) {
      console.log(err, 'err');
    }
  };
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleAddClick = () => {
    setEditingItem(null);
    setOpType('Add');
    setDrawerVisible(true);
  };
  const handleAddSuffix = (host: string, url: string) => {
    if (host&&url) {
      return host + url 
    }
  };
  const handleEditClick = (row: any) => {
    const editData = { ...row };
    if (editData.cover && typeof editData.cover === 'string') {
    }
    const editItem = {
      ...editData,
      status: Number(editData.deleted) >= 1 ? 1 : 0,
      art_class: row.banner_class, 
      banner_image: row.banner_image,
      en_banner_image: row.en_banner_image,
      jump_link: row.jump_link, 
      en_jump_link: row.en_jump_link,
    };
    setEditingItem(editItem);
    setOpType('Edit');
    setDrawerVisible(true);
  };

  const handleDetailClick = (row: any) => {
    setDetailItem(row);
    setDetailVisible(true);
  };

  const handleDrawerSubmit = async (type: string, values: any, cb: () => void) => {
    try {
      // 获取所有上传字段的值
      const uploadedImageUrls = drawerRef.current?.getUploadedImageUrls() || {};
      
      // 处理图片URL，确保格式正确
      const sanitizeUrl = (url: string) => {
        if (typeof url === 'string') {
          const idx = url.indexOf('static');
          return idx > 0 ? '/' + url.slice(idx) : url;
        }
        return url;
      };

      const formData = {
        ...values,
        banner_image: uploadedImageUrls.banner_image ? sanitizeUrl(uploadedImageUrls.banner_image) : (values.banner_image || ''),
        en_banner_image: uploadedImageUrls.en_banner_image ? sanitizeUrl(uploadedImageUrls.en_banner_image) : (values.en_banner_image || ''),
        status: values.status !== undefined && values.status !== null ? Number(values.status) : undefined, 
      };
      
      
      let res;
      if (type === 'Add') {
        res = await createApi(formData);
      } else if (type === 'Edit') {
        const editId = editingItem?.id;
        if (!editId) {
          throw new Error('编辑时缺少ID');
        }
        const editFormData = {
          ...formData,
          id: editId
        };
        res = await putApi(editFormData);
      } else {
        throw new Error('未知的操作类型');
      }
      
      message.success(`${type === 'Add' ? '新增' : '编辑'}成功`);
      cb();
      setDrawerVisible(false);
      fetchUserList();
    } catch (err: any) {
      console.error('提交失败:', err);
      message.error('操作失败');
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingItem(null);
  };

  // Sakura表单字段配置 - 使用DrawerForm
  const drawerFormFields = [
    {
      name: 'art_class',
      label: '位置',
      type: 'select' as const,
      options: getBANNER_ARTCLASSMAP(),
      required: true,
      colSpan: 6,
      colWrap: {
        labelWidth: 120,
      },
    },
    {
      name: 'banner_image',
      label: 'banner-中文',
      required: true,
      type: 'upload' as const,
      colSpan: 12,
      colWrap: {
        labelWidth: 120,
      },
      props: {
        accept: 'image/*',
        max: 1,
        autoUpload: true,
        placeholder: '请选择图片',
        showUploadProgress: false, // 不显示上传进度
        theme: 'image' // 确保使用图片上传主题
      }
    },
    {
      name: 'jump_link',
      label: '跳转链接-中文',
      required: true,
      type: 'input' as const,
      colSpan: 12,
      colWrap: {
        labelWidth: 120,
      },
    },
    {
      name: 'en_banner_image',
      label: 'banner-英文',
      required: true,
      type: 'upload' as const,
      colSpan: 6,
      colWrap: {
        labelWidth: 120,
      },
      props: {
        accept: 'image/*',
        max: 1,
        autoUpload: true,
        placeholder: '请选择图片',
        showUploadProgress: false, // 不显示上传进度
        theme: 'image' // 确保使用图片上传主题
      }
    },
    {
      name: 'en_jump_link',
      label: '跳转链接-英文',
      required: true,
      type: 'input' as const,
      colSpan: 12,
      colWrap: {
        labelWidth: 120,
      },
    },
    {
      name:'sort',
      label:"排序",
      type:'inputNumber',
      colSpan:5,
      colWrap: {
        labelWidth: 120,
      },
      props: {
        theme:'column',
      },
      help: '排序越大，官网的显示越靠前',
    },
    {
      name:'status',
      label:"状态",
      type:'radio',
      options:[{label:'启用',value:0},{label:'禁用',value:1}],
      defaultValue:0,
      colSpan:12,
      colWrap: {
        labelWidth: 120,
      },
    },

   
  ];

  

  const handleSubmitClick = async (type: string, values: any, cb: () => void) => {
    try {
      if (type == 'Add') {
      } else {
      }
    } catch (err: any) {
      if (err.response.data.code == 40050) {
        message.error('邮箱错误或不存在');
        modalRef.current.setFieldError('email', '邮箱错误');
      }
      return;
    }
    cb && cb();
    fetchUserList();
    setVisible(false);
  };
  
  // 统一的 useEffect：组件挂载时和 query 变化时都会调用
  useEffect(() => {
    fetchUserList();
  }, [query]);

  useEffect(()=>{
    getArtClassListApi().then((res: any)=>{
      setArtClassList(res.results);
      const artClassData = res.results.map((item: any)=>({
        ...item,
        i18n: item.i18n,
      })).map((item: any)=>({
        label: item.name,
        value: item.id
      }))|| [];
      setARTCLASSMAP(artClassData);
      localStorage.setItem('BANNER_ARTCLASSMAP', JSON.stringify(artClassData));
    });
  },[])
  const handleSearch = (values: any) => {
    setQuery((pre) => ({
      ...pre,
      ...values,
      page: 1,
    }));
  };
  const handleReset = () => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
    }));
  };
   // 统一的字段清除处理函数
   const handleFieldClear = (fieldName: string) => {
    setQuery((prev: any) => {
      const { [fieldName]: removed, ...rest } = prev || {};
      return { ...rest, };
    });
  };
  return (
    <>
      <Row>
        <Col style={{width: '100%'}}>
          <SakuraSearchForm
            fields={formFields}
            onFieldClear={handleFieldClear}
            onAddClick={handleAddClick}
            onSearch={handleSearch}
            onReset={handleReset}
            createField={true}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        tableHeight={272}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          onCurrentChange(current: number, pageInfo: any) {
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
          },
          onPageSizeChange(size: number) {
            setQuery((pre) => ({
              ...pre,
              page_size: size,
            }));
          },
        }}
      />
      <SakuraModal
        ref={modalRef}
        visible={visible}
        title={'订单'}
        onClose={() => {
          setVisible(false);
        }}
        onSubmit={handleSubmitClick}
        type={opType}
        initialValues={opType == 'Edit' ? editingItem : initData}
        fields={fields}
      ></SakuraModal>
      
      <SakuraDrawer
        ref={drawerRef}
        visible={drawerVisible}
        onClose={handleDrawerClose}
        title="轮播图"
        type={opType}
        initialValues={editingItem}
        width="45%"
        size="large"
        placement="right"
        destroyOnClose={true}
        showCloseBtn={true}
        showConfirmBtn={true}
        confirmText="保存"
        cancelText="取消"
        onConfirm={handleDrawerSubmit}
        onCancel={handleDrawerClose}
        drawerFormFields={drawerFormFields}
        uploadApi={uploadFileApi}
      />
      <DetailDrawer visible={detailVisible} onClose={() => setDetailVisible(false)} data={detailItem} />
      
      
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
